package com.automannn.tomcat.practice.springWeb.webStarter;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author automannn
 * @time 2021/10/13
 */
/*xxx: 注意，当容器中，注册了 HandlerAdapter，以及HandlerMapping时，将会打乱默认的SpringMvc行为*/
@Component
public class AutomanHandlerAdapter implements HandlerAdapter {

    private final AtomicInteger trigger = new AtomicInteger();

    @Override
    public boolean supports(Object handler) {
        boolean support = false;
        if (handler instanceof String){
            String value = (String) handler;
            if ("automan".equals(value)){
                support = true;
            }
        }
        return support;
    }

    @Override
    public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*xxx: 为了方便测试，偶数时，*/
        try{
            if (trigger.get()%2==0){
                //xxx: 可以在此处，直接返回响应信息，不走 ViewResolver渲染机制
                response.setStatus(200);
                String responMsg = "success adapt!  测试中文";
                System.out.println("coyoto的默认传输编码:"+response.getCharacterEncoding());
                /*xxx: response.setContentType()与直接添加头部等价 */
                response.addHeader("Content-Type","text/html;charset=utf-8");
                Cookie cookie = new Cookie("automan","aabbaac"+trigger.get());
                response.addCookie(cookie);
                response.addHeader("Set-Cookie","myTest=customSession"+trigger.get());
                response.getOutputStream().write(responMsg.getBytes());
                response.getOutputStream().flush();
                //xxx:当然也可以返回 ModelView 走viewResolver的渲染机制
                return null;
            }else {
                ModelAndView modelAndView = new ModelAndView("automanView");
                modelAndView.addObject("name", "automannn");
                return modelAndView;
            }
        }finally {
            trigger.incrementAndGet();
        }
    }

    @Override
    public long getLastModified(HttpServletRequest request, Object handler) {
        return 0;
    }
}
